package com.dsw.demo.websocket.service;

import com.alibaba.fastjson.JSONObject;
import com.dsw.demo.websocket.controller.WebSocketController;

import com.dsw.demo.websocket.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

@Component
public class MessageReceiver {
    private static final Logger logger = LoggerFactory.getLogger(MessageReceiver.class);

    /**
     * 接收消息的方法
     */
    public void receiveMessage(String message) throws IOException {
        if (StringUtil.isBlank(message)) {
            logger.info("收到一条消息redis广播消息为空");
            return;
        }
        logger.info("广播收到消息：" + message);

        JSONObject jsonTo = JSONObject.parseObject(message);
        if (!jsonTo.get("to").equals("All")) {
            sendMessageTo(jsonTo.get("msg").toString(), jsonTo.get("to").toString(), message);
        } else {
            sendMessageAll(jsonTo.get("msg").toString());
        }
    }


    public void sendMessageTo(String message, String toUser, String jsonMessage) throws IOException {
        boolean sendFlagSuccess = false;
        Set<Map.Entry<String, Session>> entries = WebSocketController.sessionMap.entrySet();
        for (Map.Entry<String, Session> entry : entries) {
            String key = entry.getKey();
            if (StringUtil.isNotBlank(key) && key.equals(toUser)) {
                Session session = entry.getValue();
                if (session != null) {
                    logger.info("发送广播消息: " + message + " 给用户: " + toUser);
                    JSONObject msgData = new JSONObject();
                    msgData.put("msg", message);
                    session.getAsyncRemote().sendText(msgData.toString());
                    sendFlagSuccess = true;
                }
            }
        }
        if (!sendFlagSuccess) {
            logger.info("redis收到广播消息，但未找到接受者，该消息在本服务丢弃……");
        }
    }

    public void sendMessageAll(String message) {
        Collection<Session> values = WebSocketController.sessionMap.values();
        for (Session session : values) {
            JSONObject msgData = new JSONObject();
            msgData.put("msg", message);
            session.getAsyncRemote().sendText(msgData.toString());
        }
    }
}
